//
//  TabBarViewController.swift
//  ezyform
//
//  Created by FengMoennig on 1/25/16.
//  Copyright © 2016 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON
class TabBarViewController: BaseTabBarController {
    var label : BaseLabel = BaseLabel()
    var lableHeight: CGFloat = 15.0
    lazy var messageAlertView: MessageAlertView = {
        let view = MessageAlertView()
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tabBar.backgroundColor = .white
        self.tabBar.layer.borderColor = UIColor.lightGray.cgColor
        self.tabBar.layer.borderWidth = 0.5
        //加Bugly的附件信息，方便问题跟踪
        SentryHelper().setCrashLogCustomInfo()
        NotificationCenter.default.addObserver(self, selector: #selector(messagePushNotification(_:)), name: NSNotification.Name(rawValue: "messagePushNotification"), object: nil)
        MessageManager.shared.getUnreadCount()//刷新Notification的badge
    }
    override func initTabBar(){
        //1.tab installation
        let installationVC = JobsListViewController()
        self.addChildViewController(childerVC: installationVC, module: APPModule.installation)
        //2.calendar
        let calendarVC = CalendarViewController()
        self.addChildViewController(childerVC: calendarVC, module: APPModule.calendar)
        //3.service jobs
        let serviceJobsVC = ServiceJobsViewController()
        self.addChildViewController(childerVC: serviceJobsVC, module: APPModule.serviceJobs)
    }
    // MAKR: - messagePushNotification
    @objc func messagePushNotification(_ notification: Notification){
        if let userInfo = notification.userInfo, let u = userInfo as? [String: AnyObject] {
            if let model = JSONDeserializer<NotificationPushModel>.deserializeFrom(dict: u) {
                if model.notifity_type == .notification_detail {//notification
                    MessageManager.shared.getUnreadCount()
                    switch model.send_mode {
                    case .important:
                        self.pushImportantAlert(model)
                    default:
                        if model.fromForgroundFlag == false {
                            //如果界面上有打开的Pop通知，就先隐藏
                            if messageAlertView.superview != nil{
                                messageAlertView.isHidden = true
                            }
                            self.toOpenDetailVC(model)
                        }
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "messageListRefreshNotification"), object: nil, userInfo: nil)
                    }
                }else {
                    if model.fromForgroundFlag { // 在前台时
                        if model.notifity_type == .installer_point_list{//installer points通知刷新Me上的badge
//                            UserDefaults.standard.set(true, forKey: APPConfig.ShowInstallerPointsNotification)
//                            UserDefaults.standard.synchronize()
//                            VersionManager.shared.updateMeTabItemBadge()
//                            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "installerPointsNotification"), object: nil, userInfo: nil)
                        }
                    }else {//当APP在后台或启动APP时，跳转；
                        self.navigationController?.popToRootViewController(animated: false)
                        self.dismiss(animated: false)
                        switch model.notifity_type {
                        case .job_list:
                            self.selectedIndex = 0
                        case .service_job_list:
                            self.selectedIndex = 1
                        case .notification_list:
                            self.selectedIndex = 2
                        case .job_detail:
                            self.tabBarController?.selectedIndex = 0
                            self.pushJobDetail(model.notifity_id)
                        case .service_job_detail:
                            self.tabBarController?.selectedIndex = 1
                            self.pushServiceJobDetail(model.notifity_id)
                        case .notification_detail:
                            self.selectedIndex = 2
                            let vc = MessageDetailViewController()
                            vc.id = model.notifity_id
                            vc.hidesBottomBarWhenPushed = true
                            self.navigationController?.pushViewController(vc, animated: false)
                        case .installer_point_list://
                            self.tabBarController?.selectedIndex = 3
                            let vc = RewardsViewController()
                            vc.hidesBottomBarWhenPushed = true
                            self.navigationController?.pushViewController(vc, animated: false)
                        }
                    }
                    
                }
            }
        }
    }
    private func toOpenDetailVC(_ model: NotificationPushModel){
        let (index, vc) = self.indexOfViewController(JobsListViewController.self)
        if let tabIndex = index, let jobsListVC = vc as? JobsListViewController{//找到Jobs list所在的index和vc
            if let window = Tool.getKeyWindow(),let rootVC = window.rootViewController as? TabBarViewController {
                if let controllers = rootVC.viewControllers, let currentNavi = controllers[rootVC.selectedIndex] as? UINavigationController{
                    if let _ = jobsListVC.presentedViewController {
                        jobsListVC.dismiss(animated: false)
                    }
                    currentNavi.popToRootViewController(animated: false)
                    if rootVC.selectedIndex != tabIndex{//如果不在tab Notification，就跳到tab Notification
                        rootVC.selectedIndex = tabIndex//
                    }
                    if let notificationNavi = controllers[rootVC.selectedIndex] as? UINavigationController{
                        let detailVC = MessageDetailViewController()
                        detailVC.id = model.notifity_id
                        detailVC.hidesBottomBarWhenPushed = true
                        detailVC.openFromNotifactionFlag = true
                        detailVC.backToPreClosure = {
                            //如果界面上有隐藏的打开的Pop通知，就显示
                            if self.messageAlertView.superview != nil{
                                self.messageAlertView.isHidden = false
                            }
                        }
                        notificationNavi.pushViewController(detailVC, animated: false)
                    }
                }
            }
            
        }
        
    }
    // Important push 弹窗
    func pushImportantAlert(_ model: NotificationPushModel,newNotificationFlag: Bool = true) {
        if let _ = APPConfig.loginInfo.popNotificationList.firstIndex(where: { $0.notifity_id == model.notifity_id}) ,newNotificationFlag{
            return
        }
        //收到消息，隐藏界面的键盘
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "keyboardWillHide"), object: nil)
        if newNotificationFlag {
            APPConfig.loginInfo.popNotificationList.insert(model, at: 0)
        }
        if messageAlertView.superview != nil{
            messageAlertView.removeFromSuperview()
        }
        messageAlertView.setData(model)
        messageAlertView.okBtnClosure = { (mod) in
            if APPConfig.loginInfo.popNotificationList.count > 0{
                APPConfig.loginInfo.popNotificationList.remove(at: 0)
            }
            self.toOpenDetailVC(mod)
        }
        if let window = Tool.getKeyWindow() {
            window.addSubview(messageAlertView)
            messageAlertView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }
    }
    
    // MARK: - push job detail
    private func pushJobDetail(_ id: String) {
        if let pvdID = Int64(id){
            JobDetailModelHelper.shared.jobDetailModel = PVDDetailModel()
            JobDetailModelHelper.shared.jobDetailModel.pvd_id = pvdID
            let vc = JobDetailViewController()
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: false)
        }
    }
    func indexOfViewController(_ checkVC: AnyClass)->(Int?, UIViewController?){
        var index: Int?
        var returnVC: UIViewController?
        if let vcs = self.viewControllers {
            //重置前，检查当前页面是否有Trading
            for i in 0..<vcs.count {
                if let navi = vcs[i] as? UINavigationController{
                    if navi.viewControllers.count > 0{
                        let vc = navi.viewControllers[0]
                        if vc.isKind(of: checkVC.self){
                            index = i
                            returnVC = vc
                            break
                        }
                    }
                }
            }
        }
        return (index, returnVC)
    }
    // MARK: - push service job detail
    private func pushServiceJobDetail(_ id: String) {
        if let serviceID = Int(id){
            let vc = ServiceJobDetailViewController()
            vc.hidesBottomBarWhenPushed = true
            ServiceDetailModelHelper.shared.serviceDetailModel = ServiceDetailModel()
            ServiceDetailModelHelper.shared.serviceDetailModel.id = serviceID
            self.navigationController?.pushViewController(vc, animated: false)
        }
        
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //只有安全区域为0的处理
        if UIDevice.getBottomAreaHeight() == 0{
            let customTabBarHeight: CGFloat = 49 + 20//49是状态栏的高度,20是预留网络是否连线的高度
            self.tabBar.frame.size.height = customTabBarHeight
            self.tabBar.frame.origin.y = view.frame.height - customTabBarHeight
        }
    }
    deinit {
        DebugLog("\(self) deinit")
        NotificationCenter.default.removeObserver(self)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}

extension BaseViewController {
    static var current: BaseViewController? {
        let window = Tool.getKeyWindow()
        var current = window?.rootViewController
        
        while (current?.presentedViewController != nil)  {
            current = current?.presentedViewController
        }
        
        if let tabbar = current as? UITabBarController , tabbar.selectedViewController != nil {
            current = tabbar.selectedViewController
        }
        
        while let navi = current as? UINavigationController , navi.topViewController != nil  {
            current = navi.topViewController
        }
        return current as? BaseViewController
    }
}
